package com.jianggujin.dbfly.mybatis.xmltag;

import java.util.List;

import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;

import com.jianggujin.dbfly.mybatis.JConfiguration;
import com.jianggujin.dbfly.mybatis.JXMLScriptBuilder;
import com.jianggujin.dbfly.mybatis.dialect.JDialect;
import com.jianggujin.dbfly.util.JDBFlyException;
import com.jianggujin.dbfly.util.dtd.JDTD;
import com.jianggujin.dbfly.util.dtd.JDTDAttribute;
import com.jianggujin.dbfly.util.dtd.JDTDElement;
import com.jianggujin.dbfly.util.dtd.JDTDEnumeration;
import com.jianggujin.dbfly.util.dtd.JDTDMixed;

/**
 * 别名节点处理器，交由方言处理
 * 
 * @author jianggujin
 *
 */
public class JAliasHandler implements JNodeHandler {

    @Override
    public void handleNode(JXMLScriptBuilder builder, XNode nodeToHandle, List<SqlNode> targetContents) {
        JConfiguration configuration = (JConfiguration) builder.getConfiguration();
        JDialect dialect = configuration.getDBFlyConfiguration().getDialect();
        if (!dialect.handleAliasNode(builder, nodeToHandle, targetContents)) {
            throw new JDBFlyException("方言{}不支持分页操作", dialect.getClass().getCanonicalName());
        }
    }

    @Override
    public void accept(JDTD dtd) {
        // 以select元素作为标准
        JDTDElement selectElement = dtd.get("select");
        JDTDMixed selectMixedContent = (JDTDMixed) selectElement.getContent();

        dtd.add(new JDTDElement("alias", new JDTDMixed(selectMixedContent), new JDTDAttribute("name"),
                new JDTDAttribute("as", new JDTDEnumeration("true", "false"))));

        for (String name : MYBATIS_INNER_ELEMENTS) {
            JDTDElement element = dtd.get(name);
            JDTDMixed mixed = (JDTDMixed) element.getContent();
            mixed.add("alias");
        }
    }
}
